import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

import '../../common/config.dart';
import '../../common/utils/toast.dart';
import '../../generated/assets.dart';

class CountryScreen extends StatefulWidget {
  const CountryScreen({super.key});

  @override
  State<CountryScreen> createState() => _CountryScreenState();
}

class _CountryScreenState extends State<CountryScreen> {
  final String title = 'Select Your Country';
  final String desc =
      'To make sure you receive the best personalized offers we need to know your language.';

  final List<_Country> countries = [
    _Country(icon: Assets.iconUsa, title: 'USA'),
    _Country(icon: Assets.iconSpanish, title: 'Spanish'),
    _Country(icon: Assets.iconIndia, title: 'India'),
    _Country(icon: Assets.iconGerman, title: 'German'),
    _Country(icon: Assets.iconOther, title: 'Other'),
  ];

  final _CountryIndex index = _CountryIndex();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: ChangeNotifierProvider.value(
          value: index,
          builder: (context, child) {
            return Column(
              children: [
                buildTitle(),
                buildContent(context),
                ElevatedButton(
                  onPressed: onClickNext,
                  child: Container(
                    width: double.infinity,
                    height: 45,
                    margin: const EdgeInsets.symmetric(horizontal: 32)
                        .copyWith(bottom: 32),
                    decoration: BoxDecoration(
                      shape: BoxShape.rectangle,
                      color: const Color(0xff4744d3),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: const Center(
                        child: Text(
                      'Keep Going',
                      style: TextStyle(color: Colors.white),
                    )),
                  ),
                ),
              ],
            );
          },
        ),
      ),
    );
  }

  Widget buildTitle() {
    return Padding(
      padding: const EdgeInsets.only(left: 30, right: 30, top: 40),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            title,
            style: const TextStyle(
              fontSize: 18,
              color: Color(0xFF7761FF),
              overflow: TextOverflow.ellipsis,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 6),
          Text(
            desc,
            style: const TextStyle(
              fontSize: 12,
              color: Color(0x79ffffff),
              overflow: TextOverflow.visible,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 16),
        ],
      ),
    );
  }

  Widget buildContent(BuildContext context) {
    return Expanded(
      child: GridView.builder(
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          childAspectRatio: 1.2,
        ),
        itemCount: countries.length,
        itemBuilder: (context, index) {
          return country(context, index);
        },
      ),
    );
  }

  Widget country(BuildContext context, int index) {
    var selectedIndex = context.watch<_CountryIndex>().value;
    var country = countries[index];
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        GestureDetector(
          onTap: () => onCountryChanged(context, index),
          behavior: HitTestBehavior.opaque,
          child: Stack(
            children: [
              Image.asset(country.icon, width: 120, height: 120),
              if (selectedIndex == index)
                Image.asset(Assets.iconSelected, width: 120, height: 120),
            ],
          ),
        ),
        const SizedBox(height: 8),
        Text(
          country.title,
          style: const TextStyle(overflow: TextOverflow.ellipsis),
        ),
      ],
    );
  }

  void onCountryChanged(BuildContext context, int index) {
    context.read<_CountryIndex>().check(index);
  }

  void onClickNext() {
    if (index.value == null) {
      showToast('Please select your country.');
      return;
    }
    context.read<Config>().stepIn(OnboardingStep.none);
    context.go('/home');
  }
}

class _Country {
  final String icon;
  final String title;

  _Country({required this.icon, required this.title});
}

class _CountryIndex extends ChangeNotifier {
  int? _value;

  int? get value => _value;

  void check(int value) {
    _value = value;
    notifyListeners();
  }
}
